//页面加载事件
window.onload=function(){
    var mySwiper = new Swiper('.swiper-container', {
        autoplay: true, //为true启动自动切换
        delay: 500, //时间
        speed:500, // 切换速度，即slider自动滑动开始到结束的时间（单位ms）
        loop: true,  //循环切换
        //effect:"flip", //可以实现3D效果的轮播
        disableOnInteraction: true,//切换方式
        
        // 如果需要分页器
        pagination: {
            el: '.swiper-pagination',
        }
    })

    //JSONServer中读取数据并渲染页面
    init()
    //滚动条滚动
    myScrollFn();
    //返回顶部点击事件
    myToTopFn();
    //跳转购物车
    jumpCart();

    //下滑到顶
    window.addEventListener("swipedown",function(){
        var st = document.documentElement.scrollTop;
        if(st == 0){
            document.getElementsByClassName("topWord")[0].style.display="block";
            setTimeout("reloadData()",1000);
        }
    })

    //上滑到底
    window.addEventListener("swipeup",function(){
        var st = document.documentElement.scrollTop;
        var screenHeight = screen.height;
        var bodyHeight = document.body.offsetHeight;
        if(st + screenHeight == bodyHeight){
            window.setTimeout(function(){
                document.getElementsByClassName("buttomWord")[0].style.display="block"
            },1500);
        }
    })
}

/**
 * 重新刷新页面
 */
function reloadData(){
    //父元素
    var box = document.getElementById("box");
    box.innerHTML = "";
    //渲染页面
    loadData();
    //当前页码恢复
    pageNo=1;
    document.getElementsByClassName("topWord")[0].style.display="none";
    document.getElementsByClassName("buttomWord")[0].style.display="none";
}


/**
 * 从JSONServer中读取数据
 */
function init(){
    //创建Ajax对象
    var req = new XMLHttpRequest();
    //封装请求
    req.open("get","http://localhost:3000/goodsList",true);
    //设置回调函数
    req.onreadystatechange=function(){
        if(req.readyState==4 && req.status==200){
            var data = JSON.parse(req.responseText);
            sessionStorage.setItem("goodsList",JSON.stringify(data));
            //渲染页面
            loadData();
        }
    }
    //发送请求
    req.send(null);
}

var totalPage;
/**
 * 读取数据并渲染页面
 */
function loadData(){
    var data = sessionStorage.getItem("goodsList");
    var jsonArr = JSON.parse(data);
    totalPage = Math.ceil(jsonArr.length/6);
    //父元素
    var box = document.getElementById("box");
    for(var item of jsonArr.slice(0,6)){
        var itemData = `<div class="item">
            <div class="pic">
                <img src="${item.goodsPic}" />
            </div>
            <p class="bh">${item.goodsNo}</p>
            <p class="jg">￥${item.goodsPrice}</p>
            <p class="spmc">${item.goodsName}</p>
            <p class="spdp">${item.shop}</p>
        </div>`;
        box.innerHTML += itemData;
    }
    //商品点击事件
    itemClickFn();
}

//购物车数据
var jsonArr = [];
/**
 * 每件商品的点击事件
 */
function itemClickFn(){
    var itemArr = document.getElementsByClassName("item");
    for(var i=0; i<itemArr.length; i++){
        // console.log(itemArr[i])
        itemArr[i].addEventListener("tap",function(){
            var itemData = {
                "goodsNo": this.children[1].innerText,
                "goodsName": this.children[3].innerText,
                "goodsPrice": this.children[2].innerText.substring(1),
                "goodsPic": this.children[0].children[0].src,
                "shop": this.children[4].innerText
            }
            // console.log(itemData);
            //添加到数组
            jsonArr.push(itemData);
            //排序
            jsonArr.sort(function(d1,d2){
                if(d1.shop > d2.shop){
                    return 1;
                }else{
                    return -1;
                }
            });
            //添加到缓存中
            localStorage.setItem("gwc",JSON.stringify(jsonArr))
        })
    }

}

var pageNo=1;
/**
 * 滚动事件
 */
function myScrollFn(){
    //滚动条滚动事件
    window.onscroll=function(){
        var st = document.documentElement.scrollTop;
        if(st > 100){
            document.getElementsByClassName("toTop")[0].style.display="block";
        }else{
            document.getElementsByClassName("toTop")[0].style.display="none";
        }
        // //滚动到顶部时触发，顶部div显示
        // if(st == 0){
        //     document.getElementsByClassName("topWord")[0].style.display="block"
        // }

        //一屏高度
        var screenHeight = screen.height;
        //整个内容高度
        var bodyHeight = document.body.offsetHeight;
        //下一屏
        //console.log(st,screenHeight, bodyHeight)
        //判断数据是否加载完毕
        if(pageNo < totalPage){
            if(st + screenHeight >= bodyHeight){
                pageNo++;
                var data = sessionStorage.getItem("goodsList");
                var jsonArr = JSON.parse(data);
                //父元素
                var box = document.getElementById("box");
                for(var item of jsonArr.slice((pageNo-1)*6,pageNo*6)){
                    var itemData = `<div class="item">
                        <div class="pic">
                            <img src="${item.goodsPic}" />
                        </div>
                        <p class="bh">${item.goodsNo}</p>
                        <p class="jg">￥${item.goodsPrice}</p>
                        <p class="spmc">${item.goodsName}</p>
                        <p class="spdp">${item.shop}</p>
                    </div>`;
                    box.innerHTML += itemData;
                }
                //商品点击事件
                itemClickFn();
            }
        }
        //滚到底部时，触发div显示
        // if(st + screenHeight == bodyHeight){
        //     window.setTimeout(function(){
        //         document.getElementsByClassName("buttomWord")[0].style.display="block"
        //     },1500);
        // }
        
    }
}

/**
 * 返回顶部点击事件
 */
function myToTopFn(){
    var timer;
    document.getElementsByClassName("toTop")[0].addEventListener("tap",function(){
        timer = setInterval(function(){
            document.documentElement.scrollTop-=10;
            if(document.documentElement.scrollTop <= 0){
                clearInterval(timer)
            }
        }, 5);
        
        
    })
}

/**
 * 跳转购物车
 */
function jumpCart(){
    document.getElementsByClassName("jumpCart")[0].addEventListener("tap",function(){
        location.href="cart.html";
    })
}